//////////////////////////////////////////////////////////////////////
//!\file FileStorageWorkData.cpp
//!\brief Reads out and saves workdata.
//!\author timmsusa@googlemail.com
//////////////////////////////////////////////////////////////////////


#include "FileStorageWorkData.hpp"
#include "FileStorageDataStream.hpp"

FileStorageWorkData::FileStorageWorkData(const QString& dataPath):
    m_DataPath(dataPath),
    m_StorageFile("collectionData.dat"),
    m_OutStream(&m_StorageFile),
    m_InStream(&m_StorageFile)
{
   // loadStorageData();
}

FileStorageWorkData::~FileStorageWorkData()
{
    saveStorageData();
}


// TODO: Read out a list of files
void FileStorageWorkData::loadStorageData()
{
    qDebug() << "FileStorageWorkData::loadMetaData()";
    if ( !m_StorageFile.open(QIODevice::ReadOnly) )
    {
        qDebug() << "File could not been opened!" << m_StorageFile.fileName();
    }

    m_InStream.setVersion(QDataStream::Qt_4_8);

    m_InStream >> m_FlacStorageList;
    foreach(const FileStorageFlac& fs, m_FlacStorageList)
    {
        qDebug() << "FlacFileStorage: \n" << fs.m_AlbumMd5 << " Raw Info: " << fs.m_AudioMd5 << fs.m_File << fs.m_MetaDataMd5;
    }
    // TODO: EXPERIMENTAL:
    m_FlacStorageList.clear();
    m_StorageFile.flush();
    m_StorageFile.close();

    if ( QFile::remove(m_DataPath) )
    {
        qDebug() << "SUCCESS: removed work data successfully to regenerate!!";
    }
    else
    {
        qDebug() << "ERROR: Failed to remove work data for regenerate!";
    }
}

// TODO: Write a list of files!
void FileStorageWorkData::addStorageData(const FlacTrack& flacTrack)
{
    qDebug() << "FileStorageWorkData::addStorageData()";
    if (!m_LastFlacTrack.compare(flacTrack))
    {
        FileStorageFlac fs(flacTrack);
        m_FlacStorageList.push_back(fs);
        m_LastFlacTrack = flacTrack;
    }
}

void FileStorageWorkData::saveStorageData()
{
    qDebug() << "FileStorageWorkData::saveStorageData";
    if ( !m_StorageFile.open(QIODevice::WriteOnly) )
    {
        qDebug() << "File could not been opened!" << m_StorageFile.fileName();
    }
    m_OutStream.setVersion(QDataStream::Qt_4_8);
    m_OutStream << m_FlacStorageList;
    m_StorageFile.flush();
    m_StorageFile.close();
}


